package cn.gmy.progect1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob;
import org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
 * D:/a/excel/mengying.xls
	file:///D:/a/excel/contact.txt
	D:/a/excel/out007
 */
public class ExcelMR2 extends Configured implements Tool {
	@Override
	public int run(String[] args) throws Exception {
		if (args.length != 3) {
			System.out.println("usage ...");
			return -1;
		}
		Configuration config = getConf();
		FileSystem fs = FileSystem.get(config);
		Path path = new Path(args[2]);
		if (fs.exists(path)) {
			fs.delete(path, true);
		}

		Job job1 = Job.getInstance(config, "Excel->Text");
		job1.setJarByClass(getClass());
		// 添加到内存中的缓存文件，可添加多个
		job1.addCacheFile(new URI(args[1]));
		//
		job1.setMapperClass(ExcelMapper.class);
//		job1.setMapOutputKeyClass(Text.class);
//		job1.setMapOutputValueClass(LongWritable.class);
		//
//		job1.setReducerClass(ExcelReducer.class);
		job1.setOutputKeyClass(LongWritable.class);
		job1.setOutputValueClass(Text.class);
		//
		job1.setInputFormatClass(ExcelInputFormat.class);
		ExcelInputFormat.addInputPath(job1, new Path(args[0]));
		FileOutputFormat.setOutputPath(job1, path);

		return job1.waitForCompletion(true)?0:1;
	}

	public static void main(String[] args) throws Exception {
		int code = ToolRunner.run(new ExcelMR2(), args);
		System.exit(code);
	}

	// 1:Mapper:
	public static class ExcelMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
		private Map<String, String> contacts = new HashMap<>();
		private Map<String, Integer> count = new HashMap<>();

		@Override
		protected void setup(Mapper<LongWritable, Text, LongWritable, Text>.Context context)
				throws IOException, InterruptedException {
			// 获取缓存文件，并将值放入Map<>中
			URI[] cache = context.getCacheFiles();
			if (cache.length > 0) {
				String path = cache[0].getPath(); // 只读取了一个缓存文件
				String fileName = path.substring(path.lastIndexOf("/") + 1);
				File file = new File(fileName);
				if (file.exists()) {
					System.out.println("添加的缓存文件是：" + fileName);
					BufferedReader br = new BufferedReader(new FileReader(file));
					String line = "";
					while ((line = br.readLine()) != null) {
						String[] str = line.split("\t");
						contacts.put(str[1], str[0]);
					}
					br.close();
				}
			}
			
			for(Entry<String, String> map:contacts.entrySet()) {
				count.put(map.getKey(), 0);
			}
		}

		@Override
		public void map(LongWritable key, Text value, Mapper<LongWritable, Text, LongWritable, Text>.Context context)
				throws IOException, InterruptedException {
			// 主叫：1 被叫：0
			String[] string = value.toString().split("\t");
			String phone = string[1];
			if (phone.startsWith("86")) {
				phone = phone.substring(2);
			}
			if (contacts.containsKey(phone)) {			
				count.put(phone, count.get(phone)+1);				
			}
		}
		
		@Override
		protected void cleanup(Mapper<LongWritable, Text, LongWritable, Text>.Context context)
				throws IOException, InterruptedException {
			for(Entry<String, Integer> map:count.entrySet()) {
				context.write(new LongWritable(map.getValue()), new Text(contacts.get(map.getKey())+"\t"+map.getKey()));
			}
		}
	}

	// 2:Reducer
	public static class ExcelReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
		private LongWritable value4 = new LongWritable();

		@Override
		protected void reduce(Text key3, Iterable<LongWritable> value3,
				Reducer<Text, LongWritable, Text, LongWritable>.Context context)
				throws IOException, InterruptedException {
			long ii = 0;
			for (LongWritable longWritable : value3) {
				ii += longWritable.get();
			}
			value4.set(ii);
			context.write(key3, value4);
		}
	}

	
}
